package com.ruoyi.web.controller.members;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.MembersConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.MembersStatus;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.members.domain.SysMembers;
import com.ruoyi.members.service.ISysMembersService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.members.service.UnionMembersService;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 会员管理
 * 
 * @author ruoyi
 * @date 2025-09-16
 */
@RestController
@RequestMapping("/system/unionMembers")
public class UnionMembersController extends BaseController {

    @Autowired
    UnionMembersService unionMembersService;
    @Autowired
    private ISysMembersService sysMembersService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 人才智库 - 会员管理 - 会员列表
     */
//    @PreAuthorize("@ss.hasPermi('system:unionMembers:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysMembers sysMembers) {
        //MybatisPlus - 条件分页查询
        Page<SysMembers> objectPage = new Page<>(sysMembers.getPageNum(), sysMembers.getPageSize());
        LambdaQueryWrapper<SysMembers> sysMembersLambdaQueryWrapper = new LambdaQueryWrapper<SysMembers>();
        if (sysMembers.getMembersName() != null) {
            sysMembersLambdaQueryWrapper.like(SysMembers::getMembersName, sysMembers.getMembersName());
        }
        if (sysMembers.getMembersNum() != null) {
            sysMembersLambdaQueryWrapper.eq(SysMembers::getMembersNum, sysMembers.getMembersNum());
        }
        if (sysMembers.getMembersTel() != null) {
            sysMembersLambdaQueryWrapper.eq(SysMembers::getMembersTel, sysMembers.getMembersTel());
        }
        //筛选会员 - 字段是会员（0）才查询
        sysMembersLambdaQueryWrapper.eq(SysMembers::getMembersIsStatus, MembersConstants.IS_MEMBERS);
        Page<SysMembers> page = sysMembersService.page(objectPage, sysMembersLambdaQueryWrapper);
        return new TableDataInfo(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
    }

    /**
     * 人才智库 - 会员管理 - 导出会员列表
     */
    @PreAuthorize("@ss.hasPermi('system:unionMembers:export')")
    @Log(title = "会员", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysMembers sysMembers) {
        //MybatisPlus - 条件分页查询
        LambdaQueryWrapper<SysMembers> sysMembersLambdaQueryWrapper = new LambdaQueryWrapper<SysMembers>();
        if (sysMembers.getMembersName() != null) {
            sysMembersLambdaQueryWrapper.like(SysMembers::getMembersName, sysMembers.getMembersName());
        }
        if (sysMembers.getMembersNum() != null) {
            sysMembersLambdaQueryWrapper.eq(SysMembers::getMembersNum, sysMembers.getMembersNum());
        }
        if (sysMembers.getMembersTel() != null) {
            sysMembersLambdaQueryWrapper.eq(SysMembers::getMembersTel, sysMembers.getMembersTel());
        }
        //筛选会员 - 字段是会员（0）才查询
        sysMembersLambdaQueryWrapper.eq(SysMembers::getMembersIsStatus, MembersConstants.IS_MEMBERS);
        List<SysMembers> list = sysMembersService.list(sysMembersLambdaQueryWrapper);
        ExcelUtil<SysMembers> util = new ExcelUtil<SysMembers>(SysMembers.class);
        util.exportExcel(response, list, "会员数据", "会员信息统计表");
    }

    /**
     * 人才智库 - 会员管理 - 详细（会员ID）
     */
//    @PreAuthorize("@ss.hasPermi('system:unionMembers:query')")
    @GetMapping(value = "/{membersId}")
    public AjaxResult getInfo(@PathVariable("membersId") Long membersId) {
        //判断会员是否存在
        LambdaQueryWrapper<SysMembers> sysMembersLambdaQueryWrapper = new LambdaQueryWrapper<SysMembers>()
                .eq(SysMembers::getMembersIsStatus, MembersConstants.IS_MEMBERS)
                .eq(SysMembers::getMembersId, membersId);
        List<SysMembers> list = sysMembersService.list(sysMembersLambdaQueryWrapper);
        if (list.size() == 0) {
            return error(MembersStatus.UNION_MEMBERS_NOT_EXIST.getInfo());
        }
        return success(list.get(0));
    }


    /**
     * 人才智库 - 会员管理 - 新增
     */
    @PreAuthorize("@ss.hasPermi('system:unionMembers:add')")
    @Log(title = "会员", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysMembers sysMembers) {
        MembersStatus membersStatus = unionMembersService.saveMembers(sysMembers);
        return MembersConstants.SUCCESS_CODE.equals(membersStatus.getCode()) ? success(membersStatus.getInfo()) : error(membersStatus.getInfo());
    }

    /**
     * 人才智库 - 会员管理 - 修改
     */
    @PreAuthorize("@ss.hasPermi('system:unionMembers:edit')")
    @Log(title = "会员", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysMembers sysMembers) {
        //根据ID查询会员
        LambdaQueryWrapper<SysMembers> sysMembersLambdaQueryWrapper = new LambdaQueryWrapper<SysMembers>()
                .eq(SysMembers::getMembersIsStatus, MembersConstants.IS_MEMBERS)
                .eq(SysMembers::getMembersId, sysMembers.getMembersId());
        List<SysMembers> list = sysMembersService.list(sysMembersLambdaQueryWrapper);
        //判断会员是否存在（ID）
        if (list.size() == 0) {
            return error(MembersStatus.UNION_MEMBERS_NOT_EXIST.getInfo());
        }
        //是否修改标志
        boolean flag = false;
        //修改工号
        if (sysMembers.getMembersNum() != list.get(0).getMembersNum()) {
            flag = true;
        }
        //修改昵称
        if (sysMembers.getMembersName() != list.get(0).getMembersName()) {
            flag = true;
        }

        //根据ID查询用户
        SysUser user = sysUserService.getById(list.get(0).getUserId());
        //判断用户是否存在
        if (user == null) {
            return error(MembersStatus.USER_NOT_EXIST.getInfo());
        }

        //修改用户部门
        user.setDeptId(sysMembers.getDeptId());
        //修改用户邮箱
        user.setEmail(sysMembers.getMembersEmail());
        //修改用户手机号码
        user.setPhonenumber(sysMembers.getMembersTel());
        //修改用户性别
        user.setSex(sysMembers.getMembersSex());
        //修改用户头像
        user.setAvatar(sysMembers.getMembersImg());
        //判断是否修改工号、昵称
        if (flag) {
            //修改用户名
            user.setUserName(sysMembers.getMembersNum().toString());
            //修改用户昵称
            user.setNickName(sysMembers.getMembersName());
        }
        //更新用户表
        sysUserService.updateById(user);
        //更新教职工表(会员)
        return toAjax(sysMembersService.updateById(sysMembers));
    }

    /**
     * 人才智库 - 教职工管理 - 删除
     */
    @PreAuthorize("@ss.hasPermi('system:unionMembers:remove')")
    @Log(title = "会员", businessType = BusinessType.DELETE)
    @DeleteMapping("/{membersIds}")
    public AjaxResult remove(@PathVariable Long[] membersIds) {
        MembersStatus membersStatus = unionMembersService.deleteSysMembersByMemsIds(membersIds);
        return MembersConstants.SUCCESS_CODE.equals(membersStatus.getCode()) ? success(membersStatus.getInfo()) : error(membersStatus.getInfo());
    }
}

